const log = require('../util/log'),
  zoroDB = require('../util/zoroDB'),
  wordDao = require('./wordDao'),
  SQL_TABLE = 'url',
  SQL_SELECT = 'select id as urlId,url,p,last_visited_time as lastVisitedTime,title from ' + SQL_TABLE,
  SQL_FIELDS = ['id', 'url', 'p', 'last_visited_time', 'title'];

exports.findByUrlId = (urlId, fn) => {
  fn = fn || (() => {
  });
  global.pool.query(SQL_SELECT + ' where id=?', [urlId], (err, rows, fields) => {
    if (err)
      throw err;
    if (rows.length > 0)
      fn(rows[0]);
    else
      fn(null)
  })
}

exports.findByUrl = (url, fn) => {
  fn = fn || (() => {
  });
  global.pool.query(SQL_SELECT + ' where url=?', [url], (err, rows, fields) => {
    if (err)
      throw err;
    if (rows.length > 0)
      fn(rows[0]);
    else
      fn(null)
  })
}

exports.insert = (url, fn) => {
  fn = fn || (() => {
  });
  global.pool.query('insert into ' + SQL_TABLE + '(url,p) values(?,?)', [url.url, url.p], (err, result) => {
    if (err)
      throw err;
    url.urlId = result.insertId;
    fn()
  })
}

exports.multiplyPByNotUrlId = (lr, urlId, fn) => {
  fn = fn || (() => {
  });
  global.pool.query('update ' + SQL_TABLE + ' set p=p*? where id!=?', [lr, urlId], (err, result) => {
    if (err)
      throw err;
    fn()
  })
}

exports.update = (obj, resolve) => {
  resolve = resolve || (() => {
  });
  if (obj.urlId) {
    zoroDB.query('update ' + SQL_TABLE + ' set p=?,last_visited_time=?,title=? where id=?', [obj.p, obj.lastVisitedTime, obj.title, obj.urlId], (err, result) => {
      if (err)
        throw err;
      resolve()
    })
  } else {
    var sql = 'update url set id=?',
      paras = [obj.id];
    for (var key in obj) {
      if (SQL_FIELDS.indexOf(key) != -1) {
        sql += ',' + key + '=?';
        paras.push(obj[key])
      }
    }
    sql += ' where id=?';
    paras.push(obj.id)
    zoroDB.query(sql, paras, (err, result) => {
      if (err)
        log(err);
      resolve()
    })
  }
}

exports.matchDuplicateUrl = resolve => {
  resolve = resolve || (() => {
  });
  global.pool.query('select url from ' + SQL_TABLE + ' group by url having count(*)>1', [], (err, rows, fields) => {
    if (err)
      throw err;
    resolve(rows)
  })
}

exports.matchUrl = (url, resolve) => {
  resolve = resolve || (() => {
  });
  global.pool.query(SQL_SELECT + ' where url=?', [url], (err, rows, fields) => {
    if (err)
      throw err;
    resolve(rows)
  })
}

exports.delete = (urlId, resolve) => {
  resolve = resolve || (() => {
  });
  log('只更新了p,last_visited_time,title')
  global.pool.query('delete from ' + SQL_TABLE + ' where id=?', [urlId], (err, result) => {
    if (err)
      throw err;
    resolve()
  })
}

exports.select = (obj, resolve) => {
  resolve = resolve || (() => {
  });
  var sql = 'select * from url where 1=1',
    paras = [];
  for (var key in obj) {
    if (SQL_FIELDS.indexOf(key) != -1) {
      sql += ' and ' + key + '=?';
      paras.push(obj[key])
    }
  }
  zoroDB.query(sql, paras, (err, rows, fields) => {
    if (err) {
      log(err)
      resolve([])
      return
    }
    rows.forEach(row => {
      exports.fillProp(row)
    })
    resolve(rows)
  })
}

exports.fillProp = url => {
  url.getWords = function (resolve) {
    if (!!this.words) {
      resolve(this.words)
      return
    }
    zoroDB.query('select * from url_word where url=?', [url.id], (err, rows, fields) => {
      var promises = [];
      rows.forEach(row => {
        promises.push(new Promise(resolve => {
          wordDao.select({
            id: row.word
          }, words => {
            wordDao.fillProp(words[0])
            resolve({
              word: words[0],
              p: row.p
            })
          })
        }))
      })
      Promise.all(promises).then(words => {
        this.words = words;
        resolve(this.words)
      })
    })
  }
  url.getCaches = function (resolve) {
    if (!!this.caches) {
      resolve(this.caches)
      return
    }
    require('./cacheDao').select({
      url: this.id
    }, caches => {
      this.caches = caches
      resolve(this.caches)
    })
  }
}
